package com.example.demo.suanfa_linked;

/**
 * @program: java_base
 * @description: 删除节点指定 value 功能
 * @author: zhouhongtao
 * @happyCreateTime: 2022/03/07 14:52
 */
public class DeleteGivenValueDemo {


    public static class Node {
        public int value;
        public Node next;

        public Node(int data) {
            this.value = data;
        }
    }

    /**
     * 删除链表内指定的值node，返回新的链表头节点
     *
     * @param head
     * @param num
     * @return
     */
    // head = removeValue(head, 2);
    public static Node removeValue(Node head, int num) {
        //  如果头结点是 要删除的值
        Node deleted = null;
        while (head != null) {
            if (head.value != num) {
                break;
            }
            // 应该造成内存泄露
            head = head.next;
        }

        // 当前的head == null or head!=null
        Node pre = head;
        Node cur = head;

        while (cur != null) {
            if (cur.value == num) {
                // 应该造成内存泄露
                deleted = cur;
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
            // 已经处理完成指针转移
            if (deleted != null && deleted.next != null) {
                deleted.next = null;
            }
        }
        return head;
    }

}
